
import paramiko,os
class SSH_CTRL:
    def __init__(self,host,username,password,port=22):
        self.host = host
        self.username = username
        self.password = password
        self.port = port
        self.sshClient=paramiko.SSHClient()
        self.sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            self.connect=self.sshClient.connect(host,username,password,port)
            print("host:{} is already connected".format(self.host)) 
        except paramiko.ssh_exception.AuthenticationException:
            self.sshClient.get_transport().auth_none(username)
        self.sftp=paramiko.SFTPClient.from_transport(self.sshClient.get_transport())
        print("{} transport is already created".format(self.host))
    '''
    上传文件
    '''
    def push(self,localpath,remotepath):
        self.sftp.push(localpath,remotepath)
    '''
    下载文件
    '''
    def pull(self,remotepath,localpath):
        self.sftp.get(remotepath,localpath)

    def exec(self,cmd):
        '''
        执行shell命令
        报错返回127,没有报错返回0
        '''
        try:
            recv=self.sshClient.exec_command(cmd,timeout=60000)
            stdin,stdout,stderr=recv
            channel=stdout.channel()
            exit_code=channel.get_exit_code()
            stdout=stdout.read().strip()
            stderr=stderr.read().strip()
            return {"status":exit_code,"stdout":stdout,"stderr":stderr}
        except:
            return {"status":exit_code,"stdout":stdout,"stderr":stderr}


    def exec_invoke(self,cmd,end_str=None):
        '''
        交互式执行命令
        '''
        try:
            ssh=self.sshClient.get_transport().open_session(end_str)
            ssh.get_pty()
            ssh.invoke_shell()
            ssh.send(cmd+'\n')
            ret=""
            while True:
                out=ssh.recv(1024)
                print(out.decode('utf-8'))
                ret=ret+out.decode('utf-8').replace('\r','')
                if end_str in out.decode('utf-8'):
                    break
            return ret
        except Exception as e:
            print("exec_invoke exception:{}".format(e))
            log(e)
            return 'Exception no return'
    '''
    再次连接
    '''
    def reconnect(self):
        print('reconnectiong'.format(self.host))
        try:
            self.close()
        except:
            pass
        finally:
            self.connect(self.port,self.user,self.passwd,self.host)
    '''
    关闭连接
    '''
    def close(self):
        self.sshClient.close()
        self.sftp.close()

def item_localpath(path):
    '''
    遍历本机指定目录

    '''
    result=set()
    for path,dirs,files in os.walk(path):
        for dir in dirs:
            print("{} folder is {}".format(path,dir))
        for file in files:
            file_path=os.path.join(path,file)
            result.add(file_path)
        return result


if __name__=="__main__":
    pass